package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1、查询出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2、组装成树形父子分类
        List<CategoryEntity> level1Menus = getChildren(0L, entities);
        return level1Menus;

    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        if(catelogId == null) { return new Long[0];}
        List<Long> list = new ArrayList<>();
        findParentPath(catelogId, list);
        return list.toArray(new Long[list.size()]);
    }

    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById( category);

        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }

    @Override
    public void findParentPath(Long catelogId, List<Long> list) {
        if( catelogId == null || catelogId == 0) {
            return ;
        }
        CategoryEntity entity = this.getById(catelogId);
        findParentPath(entity.getParentCid(), list);
        list.add(catelogId);
    }

    private List<CategoryEntity> getChildren(Long parentCatId, List<CategoryEntity> entities) {
        List<CategoryEntity> categories = new ArrayList<>();
        for (CategoryEntity entity : entities) {
            if( entity.getParentCid().equals( parentCatId)) {
                entity.setChildren( getChildren( entity.getCatId(), entities));
                categories.add( entity);
            }
        }
        if( categories.size() > 1) {
            categories.sort(Comparator.comparingInt(entity -> ((entity.getSort() == null) ? 0 : entity.getSort())));
        }
        return categories;
    }
}